const WebSocket = require("ws");
const logger = require("../utils/logger.js");

class MonitorWebSocketServer {
  constructor(server) {
    this.wss = new WebSocket.Server({
      server,
      path: "/monitor",
      verifyClient: () => true,
    });

    this.clients = new Set();
    this.history = [];
    this.maxHistory = 500;
    this.init();
  }

  init() {
    this.wss.on("connection", (ws) => {
      logger.info("[monitor] Client connected");
      this.clients.add(ws);

      // 首次连接推送历史
      try {
        ws.send(
          JSON.stringify({ type: "history", payload: this.history.slice(-200) })
        );
      } catch {}

      ws.on("close", () => {
        logger.info("[monitor] Client disconnected");
        this.clients.delete(ws);
      });

      ws.on("message", (message) => {
        // 目前无需处理客户端消息
        logger.info(`[monitor] Received client message: ${message}`);
      });
    });

    // 心跳
    setInterval(() => {
      this.wss.clients.forEach((ws) => {
        if (ws.readyState === WebSocket.OPEN) {
          try {
            ws.ping();
          } catch {}
        }
      });
    }, 30000);
  }

  addToHistory(event) {
    this.history.push(event);
    if (this.history.length > this.maxHistory) {
      this.history.splice(0, this.history.length - this.maxHistory);
    }
  }

  broadcastEvent(event) {
    this.addToHistory(event);
    const payload = JSON.stringify({ type: "event", payload: event });
    this.clients.forEach((ws) => {
      if (ws.readyState === WebSocket.OPEN) {
        try {
          ws.send(payload);
        } catch {}
      }
    });
  }

  getHistory() {
    return this.history;
  }
}

let instance = null;

function init(server) {
  if (!instance) {
    instance = new MonitorWebSocketServer(server);
  }
  return instance;
}

function publish(event) {
  if (instance) {
    instance.broadcastEvent(event);
  }
}

function getHistory() {
  return instance ? instance.getHistory() : [];
}

module.exports = { init, publish, getHistory };


